package com.cxq.boot.schedule;

import com.cxq.boot.cache.HotTagCache;
import com.cxq.boot.mapper.QuestionMapper;
import com.cxq.boot.model.Question;
import com.cxq.boot.model.QuestionExample;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * 使用 Spring Scheduled 实现定时任务，这里定时推送热门标签
 */
@Component
@Slf4j
public class HotTagsTasks {

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private HotTagCache hotTagCache;

    //使用注解添加热门标签，没10s更新一次
    @Scheduled(fixedRate = 10000)
    //@Scheduled(cron = "0 0 6,19 * * *") //每天6、19点更新
    public void reportCurrentTime() {
        log.info("The time is now {}", new Date());
        int offset = 0;
        int limit = 5;
        List<Question> questions = new ArrayList<>();

        Map<String,Integer> priorities = new HashMap<>();//设置标签根据问题和评论数的权重

        while (offset == 0 || questions.size() == limit){
            questions = questionMapper.selectByExampleWithRowbounds(new QuestionExample(),new RowBounds(offset,limit));
            for (Question question : questions) {
                String[] tags = StringUtils.split(question.getTag(), ",");
                for (String tag : tags) {
                    Integer priority = priorities.get(tag);//查看标签是否已标记
                    //权重：问题 -> 5，评论 -> 1
                    if (priority != null){
                        priorities.put(tag,priority + 5 + question.getCommentCount());
                    }else {
                        priorities.put(tag,5 + question.getCommentCount());
                    }
                }
                //将已标记标签和权重放入热标签
            }
            offset += limit;
        }
        //hotTagCache.setTags(priorities);//保存已标记标签

        //打印已标记标签的信息
        /*priorities.forEach(
                (k,v) -> {
                    System.out.print(k);
                    System.out.print(":");
                    System.out.print(v);
                    System.out.print("\n");
                }
        );*/

        hotTagCache.updateTags(priorities);

    }
}
